/**
 * Created by  lizhihang
 */

'use strict';
var express = require('express');
var router = express.Router();
var request = require('request');
var superagent = require('superagent');
var cheerio = require('cheerio');
// var async = require('async');
var logger = require('../logger');



/**
 * Get the book list of GDUT library
 *
 */

function getBookList(req, res, next) {
    var keyword = encodeURI(req.query.keyword || 'javascript')
    keyword = keyword.split('%20')[0]
    const pageNo = req.query.pageNo || 1
    if (!keyword) {
        res.send({ code: 500, message: 'keyword is required', 'data': '' })
    } else {
        const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/find_ifp_findFullPage.php?openid=gzpyp11111111&keyword=' + keyword + '&pageNo=' + pageNo + '&x=jQuery1910011918387375772_1482383950767&y=14&_=1482383950769'
        let result = [];    // 结果数据
        logger.debug('----------  start fetch data  ----------');
        request.post(baseUrl, function (err, sres) {
            if (err) {
                return logger.error('ERROR:', err)
            }

            logger.debug('----------  fetch first page success!  ----------');

            const firstData = JSON.stringify(sres.body);
            result = JSON.parse("\"" + firstData.slice(42, -3) + "\"");
            try {
                res.send({ code: 200, message: 'ok', 'data': JSON.parse(result) })
            } catch (error) {
                res.send({ code: 500, message: 'can not find this book' })
            }

        });
    }

}

// function getBookDetail(req, res, next) {
//     const ctrlRd = req.query.ctrlRd || 'K136R7DQ27';
//     const ctrlNo = req.query.ctrlRd || '714523';

//     const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/find_ifp_GetSiteColl.php?ctrlRd=' + ctrlRd + '&ctrlNo=' + ctrlNo + '&openid=gzpyp11111111&y=11&x=jQuery1910011918387375772_1482383950767&_=1482383950770'
//     let result = [];    // 结果数据
//     logger.debug('----------  start fetch data  ----------');
//     request.post(baseUrl, function (err, sres) {
//         if (err) {
//             return logger.error('ERROR:', err);
//         }

//         logger.debug('----------  fetch first page success!  ----------');

//         const firstData = JSON.stringify(sres.body);
//         result = JSON.parse("\"" + firstData.slice(43, -3) + "\"");
//         console.log(result)
//         res.send(result);
//     });
// }
function getBookDetail(req, res, next) {
    const ctrlRd = req.query.CtrlRd || 'LGIN8ETK18'
    const ctrlNo = req.query.CtrlNo || '731873'
    if (!ctrlRd) {
        res.send({ code: 500, message: 'ctrlRd is required', })
    } else {
        getBookInfo(ctrlRd).then(function (value) {
            var bookInfo = value
            getBookCollectInfo(ctrlNo).then(function (bookCollectInfo) {
                var collections = JSON.parse(bookCollectInfo.slice(1)).find_ifa_GetOpacColl2_list1

                getBookPosition(ctrlRd, ctrlNo).then(function (position) {

                    var posList = JSON.parse(position.slice(1)).find_ifa_GetSiteColl_list1

                    if (posList[0].Room) {
                        for (var i in posList) {
                            if (posList[i].Room === '5aSn5a2m5Z+O5qC35pys5Lmm5bqT') {
                                var samplePosition = new Buffer(posList[i].Site, 'base64').toString().slice(0,-1)
                            }
                            if (posList[i].Room === '5aSn5a2m5Z+O6Ieq54S256eR5a2m5Lmm5bqT') {
                                var naturePosition = new Buffer(posList[i].Site, 'base64').toString().slice(0,-1)
                            }
                            if (posList[i].Room === '6b6Z5rSe5Lq65paH56eR5a2m5Lmm5bqT') {
                                var DragonHumanPosition = new Buffer(posList[i].Site, 'base64').toString().slice(0,-1)
                            }
                            if (posList[i].Room === '5aSn5a2m5Z+O5Lq65paH56eR5a2m5Lmm5bqT') {
                                var MegeHumanPosition = new Buffer(posList[i].Site, 'base64').toString().slice(0,-1)
                            }
                        }

                        console.log(samplePosition)
                        for (var i in collections) {
                            if (collections[i].Room === "大学城样本书库") {
                                collections[i].position = samplePosition
                            }
                            else if (collections[i].Room === "大学城自然科学书库") {
                                collections[i].position = naturePosition
                            } else if (collections[i].Room === "龙洞人文科学书库") {
                                collections[i].position = DragonHumanPosition
                            } else if (collections[i].Room === "大学城人文科学书库") {
                                collections[i].position = MegeHumanPosition
                            }else {
                                collections[i].position = '未查询到位置信息'
                            }
                        }
                        bookInfo.DetailCollection = collections
                        res.send(bookInfo)
                    } else {
                        for (var i in collections) {
                            collections[i].position = '未查询到位置信息'
                        }
                        bookInfo.DetailCollection = collections
                        res.send(bookInfo)
                    }


                })
            })
        })
    }
}
/**
 * 查找书籍的详细信息
 * @param {char} ctrlRd 
 */
function getBookInfo(ctrlRd) {
    const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/find_ifp_GetDetail.php?ctrlRd=' + ctrlRd + '&openid=gzpyp11111111&y=11&x=jQuery19104649176793256704_1492486492820&_=1492486492824'
    logger.debug('----------  start fetch data  ----------');
    return new Promise((resolve, reject) => {
        request.post(baseUrl, function (err, sres, ctrlNo) {
            if (err) {
                return logger.error('ERROR:', err);
            }

            logger.debug('----------  fetch first page success!  ----------');

            const firstData = JSON.stringify(sres.body);
            var result = JSON.parse("\"" + firstData.slice(43, -3) + "\"");
            // console.log(result)
            var result = JSON.parse(result.slice(5))


            var newBookString = new Buffer(result.DetailIntro, 'base64').toString()

            var $ = cheerio.load(newBookString);

            result.DetailIntro = $('hr').next()[0].prev.data + ($('hr').next()[0].next.data?$('hr').next()[0].next.data:'')

            if (!result.DetailIntro) {
                var $ = cheerio.load(newBookString);
                result.DetailIntro = $('p')[0].children[0].data + ($('p')[1].children[0].data?$('p')[1].children[0].data:'')
            }

            //$ = cheerio.load(result.DetailIntro);
            resolve(result)
        });
    })
}

function getBookCollectInfo(ctrlNo) {

    const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/find_ifp_GetOpacColl2.php?ctrlNo=' + ctrlNo + '&openid=gzpyp11111111&x=jQuery19104649176793256704_1492486492820&y=11&_=1492486492823'
    logger.debug('----------  start fetch data  ----------');
    return new Promise((resolve, reject) => {
        request.post(baseUrl, function (err, sres) {
            if (err) {
                return logger.error('ERROR:', err);
            }

            logger.debug('----------  fetch first page success!  ----------');

            const firstData = JSON.stringify(sres.body);
            let result = JSON.parse("\"" + firstData.slice(43, -3) + "\"");
            resolve(result)
        });
    })
}


/**
 * 功能：查找课本的位置信息
 * @param {char} ctrlRd 
 * @param {char} ctrlNo 
 */
function getBookPosition(ctrlRd, ctrlNo) {
    const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/find_ifp_GetSiteColl.php?ctrlRd=' + ctrlRd + '&ctrlNo=' + ctrlNo + '&openid=gzpyp11111111&y=11&x=jQuery19104649176793256704_1492486492820&_=1492486492822'

    logger.debug('----------  start fetch data  ----------');
    return new Promise((resolve, reject) => {
        request.post(baseUrl, function (err, sres) {
            if (err) {
                return logger.error('ERROR:', err);
            }

            logger.debug('----------  fetch first page success!  ----------');

            const firstData = JSON.stringify(sres.body);
            var result = JSON.parse("\"" + firstData.slice(43, -3) + "\"");
            resolve(result)
        });
    })
}


function frequency(req, res, next) {

    const baseUrl = 'http://weixin.zhaobenshu.com/WeiXin/gdut/page/find/interface/keyword_ifp_GetList.php?&x=jQuery191013034331115739795_1492483353483&y=14&_=1492483353484'
    logger.debug('----------  start fetch data  ----------');
    request.post(baseUrl, function (err, sres) {
        if (err) {
            return logger.error('ERROR:', err);
        }

        logger.debug('----------  fetch first page success!  ----------');

        const firstData = JSON.stringify(sres.body);
        var result = JSON.parse("\"" + firstData.slice(43, -3) + "\"");
        res.send(result);
    });
}
// /**
//  * 功能：提供书籍的热搜功能
//  * @param {*} req 
//  * @param {*} res 
//  * @param {*} next 
//  */

// function hotsearch(req, res, next) {
//     const keyword = encodeURI(req.query.keyword || 'javascript')
//     const baseUrl = 'http://www.szlib.org.cn/Search/searchshowAUTO.jsp?v_tablearray=bibliosm,serbibm,apabibibm,mmbibm,&v_index=title&sortfield=score&sorttype=desc&term=' + keyword
//     logger.debug('----------  start fetch data  ----------');
//     request.post(baseUrl, function (err, sres) {
//         if (err) {
//             return logger.error('ERROR:', err);
//         }

//         logger.debug('----------  fetch first page success!  ----------');

//         const result = JSON.parse(sres.body);
//         res.send(result);
//     });
// }

/**
 * 获取找本书热搜
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function getHotSearch(req, res, next) {
    const baseUrl = 'http://222.200.122.34:7781//Logs/stvisitkey_ifa_GetList.ashx';
    request.get(baseUrl, function( err, sres ){
        if(err){
            return logger.error('ERROR:', err);
        }
        var result = JSON.parse(sres.body);
				result.stvisitkey_ifa_GetList_list1 = result.stvisitkey_ifa_GetList_list2
        res.send(result);
    });
}
/**
 * 获取借阅书本信息
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function borrowedBook (req, res, next) 
{
    var cookie = req.body.cookie;
    const baseUrl = 'http://222.200.122.10:7771/user/bookborrowed.aspx';
    superagent.get(baseUrl)
        .set('Cookie', cookie)
        .end(function(err, sres){
            // console.log(sres.text);
            // TODO 匹配tr标签
            let data = {}
            let data2 = {}
            data2 = sres.text.match(/<td(?:.*?)?>(.*?)<\/td>/);
            data = sres.text.match(/[^>]+.(?=(<\/td))/)
            var $ = cheerio.load(sres.text);
            var slideListData = [];

            slideListData.push({
                td1: $('table').find("tr").eq(0).find("td").eq(0).html(),
                td2: $('table').find("tr").eq(0).find("td").eq(1).html(),
                td3: $('table').find("tr").eq(0).find("td").eq(2).html(),
                td4: $('table').find("tr").eq(1).find("td").eq(0).html(),
                td5: $('table').find("tr").eq(1).find("td").eq(1).html(),
                td6: $('table').find("tr").eq(1).find("td").eq(2).html(),
            });
            console.log(slideListData)
            res.send(slideListData)
            // console.log(data)
            // console.log(data2)
            // res.send(data2)
        })
}
/**
 * 图书馆登录 return cookie
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function gdutlibLogin (req, res, next)
{
    var username = req.body.username;
    var password = req.body.password;
    if( username && password ){
        getGDUTlibCookie(username, password).then(function(value){
            var cookie = value;
            if(cookie != ''){
                res.send({ code:200, message:'登录成功', data:cookie});
            }else{
                res.send({ code:500, message:'登录失败'})
            }
        })
    }else{
        res.send({code:504, message:'缺少参数'})
    }
}

/**
 * 获取图书馆登录cookie
 * @param {char} username 
 * @param {char} password 
 */
function getGDUTlibCookie(username, password)
{
    return new Promise ((resolve, reject) => {
    const baseUrl = 'http://222.200.122.10:7771/internalloginAjax.aspx';
    let formData = {
            username: username,
            password: password,
        }
		console.log('formData:'+formData.username);
    superagent.post(baseUrl)
        .set('Referer', 'http://222.200.122.10:7771/internal_login.aspx')
				.set('Content-Type', 'application/x-www-form-urlencoded')
        .type("form")
        .send(formData)
        .end(function (err, res) {
            if (err) {
                throw err
            }
            console.log('test')
            console.log(res.header);
            console.log('gudtlib' + res.header['set-cookie']);
            var cookie = res.header['set-cookie'];
            if(cookie){
                resolve(cookie)
            }else{
                resolve(0)
            }
           
        })
    });
}

module.exports = { getBookList, getBookDetail, frequency, getHotSearch, gdutlibLogin, borrowedBook };
